/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.mall.shopping.web.CartAction
   Module Description   :

   Date Created      : 2009/12/27
   Original Author   :  ellen.li
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.mall.shopping.web;

//import static org.junit.Assert.fail;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.geronimo.mail.util.Base64;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.campaign.entity.Campaign;
import com.yaodian100.ec.campaign.entity.CampaignDiscount;
import com.yaodian100.ec.campaign.entity.CampaignProduct;
import com.yaodian100.ec.campaign.service.CampaignDiscountService;
import com.yaodian100.ec.campaign.service.CampaignProductService;
import com.yaodian100.ec.campaign.service.CampaignService;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.cobranding.entity.DPNStore;
import com.yaodian100.ec.cobranding.service.DPNService;
import com.yaodian100.ec.creditcard.entity.Creditcard;
import com.yaodian100.ec.creditcard.entity.CreditcardDetail;
import com.yaodian100.ec.creditcard.service.CreditcardDetailService;
import com.yaodian100.ec.creditcard.service.CreditcardService;
import com.yaodian100.ec.delivery.service.DeliveryRuleService;
import com.yaodian100.ec.givebonus.entity.BonusSetting;
import com.yaodian100.ec.member.entity.AddressBook;
import com.yaodian100.ec.member.entity.Balance;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.AddessService;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.payment.service.TransferService;
import com.yaodian100.ec.product.entity.AddPurchaseSetting;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.entity.SpecificationMajor;
import com.yaodian100.ec.product.service.AddPurchaseSettingService;
import com.yaodian100.ec.product.service.Product2Service;
import com.yaodian100.ec.shelf.entity.Shelf;
import com.yaodian100.ec.shelf.service.ShelfService;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.entity.ViewEcCartDetail;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.ec.timelimitsale.service.TimeLimitSaleService;
import com.yaodian100.mall.member.util.UserData;
import com.yaodian100.mall.member.web.UserLoginData;

/**
 * @author ellen.li
 * 
 */
public class CopyOfCartAction extends ActionSupport implements Preparable {

	private static final long serialVersionUID = -6041158392857156610L;
	private final Logger logger = LoggerFactory.getLogger(CopyOfCartAction.class);
	@Autowired
	private Product2Service product2Service;
	@Resource
	private CategoryService categoryService;
	@Resource
	private AddPurchaseSettingService addPurchaseSettingService;
	@Resource
	private BaseManager baseMgr;
	@Autowired
	private DPNService dpnService;
	@Autowired
	private CampaignService campaignService;
	private Product product;
	private Specification specification;
	private MemberService memberService;
	private Member member;
	private CartOrdersService cartordersService;
	private CampaignProductService campaignProductService;
	private CartOrders cartOrders;
	private CommonCriteria crit;
	private String actionResult;
	private DomainService<Menu> menuService; // 與 setter
	private Menu productTpMenu; // 與 getter, setter
	private List<CartOrderProductDetail> cartOrderProductDetailList;
	private List<CartOrderProduct> cartOrderProductList;
	private List<String> timeLimitCartOrderProductList;
	// 前端頁面參數
	private String fromProduct;
	private String fromCategory;
	private String[] itemNo;
	private String[] specNo;
	private String[] qty;
	private String[] categoryPath;
	private String[] type;
	private String presents;
	private String addOns;
	private ArrayList<String> carItemList;
	private List<ViewEcCartDetail> viewEcCartList; // ViewEcCartDetail
	private ArrayList<String> viewEcCartNewList = new ArrayList<String>();
	private String delCartProdId;
	private String delCartOrderProdId;
	private String updateCartData;
	private String chkInveny;
	private Map<String, String> showWeightMap;
	private Map<String, Map<String, List<String>>> pickMap;
	private String moveCartResult;
	private String productId;
	private String rsPage;
	private boolean needValidateNum;
	private String ccode;
	private String ccodeResult;
	private Map<String, String> provincesMap;
	private String deliveryType;
	private boolean canUseCod;// 是否可使用cod付款
	private String creditcardDetailId;// 分期活動明細id
	private String period;// 分期期數
	private String creditcardDetailResult;// 回傳分期銀行判斷結果
	private Creditcard creditcard;// 信用卡分期
	private Menu billBankCodeMenu; // 快钱menu code
	private String finalTotalAmount;// 付款总额(信用卡分期检核用)
	private CreditcardDetail creditcardDetailEntity;
	private Float tempTotalAmount = 0.0f;
	private boolean chkAvailableDetails;
	// 商品重量
	private String cartId;
	private Map<String, String> resultMap;
	private BigDecimal totalWeight;
	private String cmpPordId;
	private Product cmpPord;// 满额购商品
	private String itemExists;
	private String tlpCode;// 限時搶購回傳代碼
	private String addCartResult;
	private String rs;

	// 滿額購
	private AddPurchaseSetting addPurchaseSetting;
	private List<CampaignProduct> campaignProductList;
	private int campaignProductSize;
	private List<Product> campainProductDataList;// 滿額購商品列表
	// private List<Shelf> campainShelfDataList;// 滿額購商品上架售價列表
	private ShelfService shelfService;
	private List<String> campainProductPriceList;// 滿額購商品上架售價列表
	private String addCmpnPrdctId;
	private String cmpUuid;// 滿額購uuid
	private String cmpSpecId;// 滿額購specid

	// 滿額購dialog
	private CampaignProduct campaignProduct;
	private String cmpnPrdctId;
	private List<SpecificationMajor> prodMajors;
	private Map<String, SpecificationInventory> prodInvMap;
	private boolean isVolumeOfProduct;
	// 立即購買
	private ArrayList<String> buyNowList;
	private int countBuyNow;
	// 会员积分
	private int canUse;
	private String overOneThousand = "N";
	private TransferService transferService;
	// 地址簿
	private List<AddressBook> abList;
	private AddressBook lastAddressBook;
	private String province;
	private String city;
	private String district;

	private String cartOrderProdId;
	private String prodSpecId;
	private String prodQty;
	private String addonProdId;

	private String buyNowCartId;
	private List<String> tlpList;
	private BonusSetting bonusSetting;
	private Campaign bonusCampaign;
	@Autowired
	private CampaignDiscountService campaignDiscountService;
	@Autowired
	private TimeLimitSaleService timeLimitSaleService;
	@Autowired
	private AddessService addressService;
	@Autowired
	private DeliveryRuleService deliveryRuleService;
	@Autowired
	private CartOrdersService cartOrderService;
	@Autowired
	private CreditcardService creditcardService;
	@Autowired
	private CreditcardDetailService creditcardDetailService;

	/**
	 * 活动集合物件 Campaign Entity List
	 */
	private List<CampaignDiscount> campaignList;
	/**
	 * 活动集合物件 Campaign Entity
	 */
	private CampaignDiscount campaignDiscount;

	// COD﹣收取手續費
	private BigDecimal codFee = new BigDecimal(0);

	private String cart100Items = "";// 百分点推荐引擎

	// 检核是否做过手机验证
	private boolean ismobileVaild;

	private Map<String, String> prodVolumeMap;// 大材积商品

	CartOrders addPromotionProduct(CartOrders cartOrders, String cmpUuid, String specId) throws Exception {
		if (StringUtils.isNotBlank(cmpUuid)) {
			boolean hasFive = false;
			for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
				if (cop.getProdTp().equals("5")) {
					hasFive = true;
					break;
				}
			}
			if (!hasFive) {
				cartOrders = cartordersService.addPromoteProduct(cartOrders, cmpUuid, "5", specId);
				cartOrders = cartordersService.save(cartOrders);
			}
		}
		return cartOrders;
	}

	Map<String, String> buyNowWeight(String buyNowList, String cartId) throws Exception {
		CartOrderProduct cartOrderProduct = null;
		CartOrderProductDetail cartOrderProductDetail = null;
		cartOrderProductList = new ArrayList<CartOrderProduct>();
		cartOrderProductDetailList = new ArrayList<CartOrderProductDetail>();

		// 商品明细 类型 属性 单价 数量 小计
		// 【CACA BECCA】★摇滚Star~闪亮星星铆钉百搭~蓝色,0,39,298.5,1,298.5,00000407,217,490
		String[] buyNowArray = null;
		String[] buyNowListArray = StringUtils.split(buyNowList, ";");
		Specification spec = null;
		for (String buyNow : buyNowListArray) {
			buyNowArray = buyNow.split(",");
			product = product2Service.get(buyNowArray[0]);
			spec = product2Service.getSpecification(Long.parseLong(buyNowArray[1]));
			if (StringUtils.contains("0456", buyNowArray[3])) {
				cartOrderProduct = new CartOrderProduct();
				cartOrderProduct.setCartId(cartId);
				cartOrderProduct.setProdName(product.getProductName());
				cartOrderProduct.setProdTp(buyNowArray[3]);
				cartOrderProduct.setProdSpecName(spec.getSpecificationName());
				cartOrderProduct.setQty(Integer.parseInt(buyNowArray[2]));
				cartOrderProduct.setProdId(buyNowArray[0]);
				cartOrderProductList.add(cartOrderProduct);
			}
			cartOrderProductDetail = new CartOrderProductDetail();
			// cartOrderProductDetail.setCartId(cartId);
			cartOrderProductDetail.setProdName(product.getProductName());
			cartOrderProductDetail.setDetailTp(buyNowArray[3]);
			cartOrderProductDetail.setProdSpecName(spec.getSpecificationName());
			cartOrderProductDetail.setQty(Integer.parseInt(buyNowArray[2]));
			cartOrderProductDetail.setProdId(buyNowArray[0]);
			cartOrderProductDetailList.add(cartOrderProductDetail);
		}
		Map<String, String> weightMap = cartordersService.showProductWeight(cartOrderProductDetailList);
		return weightMap;
	}

	// 達芙妮
	public String orderBuyDaphne() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		userData.writeRawValue(UserData.NAME_YAODIAN100_TL_RS, ServerValue.getFrontContextPath()
				+ "/product/product.do?productId=" + itemNo[0]);
		String memberId = StringUtils.defaultString(userData.getMemberId());
		List<String> addOnProductIds = new ArrayList<String>();
		String[] addOnsSplit = null;
		if (addOns != null) {

			addOnsSplit = addOns.split(",");
			for (String str : addOnsSplit) {
				addOnProductIds.add(StringUtils.remove(str, "\""));
			}

		}
		cartOrders = cartordersService.getCart(memberId, null);

		if (cartOrders != null) {
			// 不需初始化購物車
		} else {
			cartordersService.createCart(memberId, null, null, null, 0, null, null);

		}
		String categoryId = NumberUtils.isNumber(categoryPath[0]) ? categoryPath[0] : StringUtils
				.parseNumber(categoryPath[0]);
		if ("6".equals(type[0])) {
			cartOrders = cartordersService.createCart(memberId, itemNo[0], addOnProductIds, Long.valueOf(specNo[0]), Integer
					.valueOf(qty[0]), categoryId, null);
		} else {
			cartOrders = cartordersService.createCart(memberId, itemNo[0], null, Long.valueOf(specNo[0]), Integer
					.valueOf(qty[0]), categoryId, addOnProductIds);
		}
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		optional.put("rsPage", "buy");
		cartOrders = cartordersService.calculateCart(cartOrders, optional);
		// 未滿一定金額無法使用到店取貨
		if (cartOrders.getAmount().compareTo(ServerValue.getDaphneLimitPrice()) != 1) {
			return forceReloadCart();
		}
		if (StringUtils.isBlank(request.getParameter("prtFlag"))) {
			String invntryInfo = cartordersService.checkSpecInventory(cartOrders.getCartId(), "", optional, "step0");
			actionResult = invntryInfo;
		} else {
			cartOrders = updPrtQty(cartOrders);
			cartOrders = cartordersService.calculateCart(cartOrders, optional);
			actionResult = "";
		}
		request.setAttribute("isBuyNow", "true");
		request.setAttribute("storeId", userData.readRawValue("storeId"));// 达芙妮店代
		if (StringUtils.isNotBlank(userData.readRawValue("storeId"))) {
			CommonCriteria crit = new CommonCriteria();
			crit.addEq("storeId", userData.readRawValue("storeId"));
			List<DPNStore> DPNStores = dpnService.getDPNStoretList(crit);
			if (DPNStores.size() > 0) {
				request.setAttribute("storeAreaInit", DPNStores.get(0).getStoreArea());
			}
			// 达芙妮收货人资料
			String receiverdate = StringUtils.defaultString(new String(Base64.decode(userData.readRawValue("receiverData")
					.getBytes())));
			request.setAttribute("receiverData", receiverdate);
		}
		// 限時搶購
		if (timeLimitSaleService.isTimeLimitSale(itemNo[0])) {
			timeLimitCartOrderProductList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());
		}
		BigDecimal cartSumAmount = cartOrders.getAmount().add(cartOrders.getDiscount());

		// 会员积分折抵限制
		bonusCampaign = campaignService.getActiveBonusCampaignByM02(optional);

		// 是否需要輸入驗證碼
		needValidateNum = cartordersService.needValidateNum(cartOrders.getCartId());

		// 检核是否做过手机验证
		ismobileVaild = member.getIsMobileMember();
		return "orderBuyDaphne";

	}

	/**
	 * 赠品不足-更新赠品数量
	 * 
	 * @param cartOrders
	 * @return
	 */
	CartOrders updPrtQty(CartOrders cartOrders) {
		for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
			if ("2".equals(cop.getProdTp())) {// 行销活动赠品
				SpecificationInventory inv = product2Service.getSpecificationInventory(cop.getProdId(), Long.parseLong(cop
						.getProdSpecId()));
				if (inv.getInventory() <= 0) {
					cop.setQty(0);
				} else {
					cop.setQty(1);
				}
			}
			for (CartOrderProductDetail copd : cop.getDetails()) {
				if ("2".equals(copd.getDetailTp())) {// 搭售赠品、行销活动赠品
					SpecificationInventory inv = product2Service.getSpecificationInventory(copd.getProdId(), Long.parseLong(copd
							.getProdSpecId()));
					if (inv.getInventory() <= 0) {
						copd.setQty(0);
					} else {
						if (!copd.getProdId().equals(cop.getProdId())) {// 搭售赠品
							if (copd.getQty() > cop.getQty()) {
								copd.setQty(cop.getQty());
							}
							if (inv.getInventory() < copd.getQty()) {
								copd.setQty(inv.getInventory());
							}
						}
					}
				}
			}
		}
		cartOrders = cartordersService.update(cartOrders);
		return cartOrders;
	}

	public String addCart() throws Exception {
		try {

			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			UserData userData = new UserData(request, response);
			userData.writeRawValue(UserData.NAME_YAODIAN100_TL_RS, ServerValue.getFrontContextPath() + "/shopping/cart.do");
			// 瀏覽器裏已有cookie就放入tmpCartid
			String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));
			String memberId = StringUtils.defaultString(userData.getMemberId());
			// viewEcCartList = null;

			// ADDONS 改為只放addon product id
			List<String> addOnProductIds = new ArrayList<String>();
			String[] addOnsSplit = null;
			if (addOns != null) {
				addOns = addOns.replaceAll("\"", "");
				addOnsSplit = addOns.split(",");
				for (String str : addOnsSplit) {
					addOnProductIds.add(str);
				}
			}

			// 帳號登入
			if (null != userData && StringUtils.isNotBlank(memberId)) {
				member = memberService.get(memberId);
				if (null != member) {
					cartOrders = cartordersService.getCart(member.getMemberId(), null);
					if (null == cartOrders) {// 已登入且會員從未加入過購物車
						cartOrders = cartordersService.createCartForStep1(memberId, null, null, null, 0, null, null);
					}
					boolean isItemExist = false;
					if (itemNo != null && !"6".equals(type[0])) {
						// if (null != cartOrders) {
						for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
							// if (cop.getProdId().equals(itemNo[0])) {
							if (cop.getProdSpecId().equals(specNo[0])) {
								isItemExist = true;
								break;
							}
						}
						// }
					}
					if (!isItemExist) {

						if (null != itemNo) {
							String categoryId = NumberUtils.isNumber(categoryPath[0]) ? categoryPath[0] : StringUtils
									.parseNumber(categoryPath[0]);
							if (!"6".equals(type[0])) {
								cartOrders = cartordersService.addProductForStep1(member.getMemberId(), cartOrders.getCartId(),
										itemNo[0], null, Long.valueOf(specNo[0]), Integer.valueOf(qty[0]), categoryId, addOnProductIds);
							} else {
								cartOrders = cartordersService.addProductForStep1(member.getMemberId(), cartOrders.getCartId(),
										itemNo[0], addOnProductIds, Long.valueOf(specNo[0]), Integer.valueOf(qty[0]), categoryId, null);
							}
							// 记录商品類別cookie
							userData.writeRawValue("fromProduct", categoryService.get(Long.parseLong(categoryId)).getCategoryPath()
									.split("/")[0]);
						}
						if (StringUtils.isNotBlank(cmpUuid) && StringUtils.isNotBlank(cmpSpecId)) {
							cartOrders = addPromotionProduct(cartOrders, cmpUuid, cmpSpecId);
						}

					}
				}

			} else {// 無帳號登入（未登入）
				if (null != itemNo) {

					cartOrders = cartordersService.getCart(null, tmpCartid);

					String categoryId = NumberUtils.isNumber(categoryPath[0]) ? categoryPath[0] : StringUtils
							.parseNumber(categoryPath[0]);
					if (cartOrders == null) {
						if (!"6".equals(type[0])) {
							cartOrders = cartordersService.createCartForStep1(memberId, itemNo[0], null, Long.valueOf(specNo[0]),
									Integer.valueOf(qty[0]), categoryId, addOnProductIds);
						} else {
							cartOrders = cartordersService.createCartForStep1(memberId, itemNo[0], addOnProductIds, Long
									.valueOf(specNo[0]), Integer.valueOf(qty[0]), categoryId, null);
						}
						if (StringUtils.isNotBlank(cmpUuid) && StringUtils.isNotBlank(cmpSpecId)) {
							cartOrders = addPromotionProduct(cartOrders, cmpUuid, cmpSpecId);
						}
					} else {
						if (!"6".equals(type[0])) {
							cartOrders = cartordersService.addProductForStep1(null, cartOrders.getCartId(), itemNo[0], null, Long
									.valueOf(specNo[0]), Integer.valueOf(qty[0]), categoryId, addOnProductIds);
						} else {
							cartOrders = cartordersService.addProductForStep1(null, cartOrders.getCartId(), itemNo[0],
									addOnProductIds, Long.valueOf(specNo[0]), Integer.valueOf(qty[0]), categoryId, null);
						}
						if (StringUtils.isNotBlank(cmpUuid) && StringUtils.isNotBlank(cmpSpecId)) {
							cartOrders = addPromotionProduct(cartOrders, cmpUuid, cmpSpecId);
						}
					}
					userData.writeRawValue("cartid", cartOrders.getCartId());
					// 记录商品類別cookie
					userData.writeRawValue("fromProduct", categoryService.get(Long.parseLong(categoryId)).getCategoryPath()
							.split("/")[0]);
				} else {
					cartOrders = cartordersService.getCart(null, tmpCartid);

					if (null != cartOrders) {
						if (StringUtils.isNotBlank(cmpUuid) && StringUtils.isNotBlank(cmpSpecId)) {
							cartOrders = addPromotionProduct(cartOrders, cmpUuid, cmpSpecId);
						}
					}
				}
			}
			// 记录购物车商品数量
			cartOrders = cartordersService.get(cartOrders.getCartId());
			userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
			addCartResult = "success";
		} catch (Exception e) {
			addCartResult = "failure";
			e.printStackTrace();
			throw e;
		}
		return "addCart";
	}

	/**
	 * 購物車 好花的購物車
	 * 
	 * @return
	 * @throws Exception
	 */
	public String cart() throws Exception {
		if (cmpUuid != null && cmpUuid.length() > 0) {
			addCart();
		}
		return forceReloadCart();
	}

	public String checkCart() throws Exception {
		try {

			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			UserData userData = new UserData(request, response);
			// 瀏覽器裏已有cookie就放入tmpCartid
			String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));

			String memberId = StringUtils.defaultString(userData.getMemberId());
			CartOrders tmpCartOrders = new CartOrders();
			viewEcCartList = null;
			// 帳號登入
			if (null != userData && StringUtils.isNotBlank(memberId)) {
				member = memberService.get(memberId);
				if (null != member) {
					tmpCartOrders = cartordersService.getCart(member.getMemberId(), null);
					if (null == tmpCartOrders) {// 已登入且會員從未加入過購物車
						tmpCartOrders = cartordersService.createCart(memberId, null, null, null, 0, null, null);// createNewCartOrders("",
						// userData.getMemberId());

					} else {
						if (tmpCartid.equals(tmpCartOrders.getCartId())) {// 已登入,且cartOrders內有member的購物車資料,則繼續新增原車
							if (null != itemNo) {
								if (isItemExists(tmpCartOrders, itemNo, specNo, tmpCartid)) {
									itemExists = "true";
								} else {
									itemExists = "false";
								}
							}
						} else {
							if (StringUtils.isNotBlank(tmpCartid)) {// 已登入,且cartOrders內有member的購物車資料與userData內的cartid cookie不符
								// processMoveTmpCartToCartOrder(tmpCartid, cartOrders.getCartId(), cartordersService, userData);//
								// 則將暫存車移至原車
								itemExists = "false";
							} else {
								if (null != itemNo) {
									if (isItemExists(tmpCartOrders, itemNo, specNo, tmpCartid)) {
										itemExists = "true";
									} else {
										itemExists = "false";
									}

								}
							}

						}
					}
				}
			} else {// 無帳號登入
				if (null != itemNo) {

					if (isItemExists(null, itemNo, specNo, tmpCartid)) {
						itemExists = "true";
					} else {
						itemExists = "false";
					}

				}
			}

		} catch (Exception e) {
			e.printStackTrace();

			throw e;

		}
		if (itemExists == null) {
			itemExists = "false";
		}

		return "itemExists";

	}

	public String checkTlpCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String tmpCartId = StringUtils.defaultString(userData.readRawValue("cartid"));
		String memberId = StringUtils.defaultString(userData.getMemberId());
		// 瀏覽器裏已有cookie就放入tmpCartid
		// 帳號登入
		if (StringUtils.isNotBlank(memberId)) {
			cartOrders = cartordersService.getCart(memberId, null);
		} else {
			if (StringUtils.isNotBlank(tmpCartId)) {
				cartOrders = cartordersService.getCart(null, tmpCartId);
				if (null == cartOrders) {
					cartOrders = new CartOrders();
				}
			}
		}

		if (null == cartOrders) {
			cartOrders = new CartOrders();
		} else {
			Map<String, String> optional = new HashMap<String, String>();
			optional.put("domain", request.getServerName());
			optional.put("cookie", userData.getApplySource());
			cartOrders = cartordersService.calculateCart(cartOrders, optional);
		}
		if (StringUtils.equals("product", rs)) {
			tlpCode = timeLimitSaleService.canAdd(itemNo[0], memberId, cartOrders.getCartOrderProducts());
		} else {
			tlpCode = timeLimitSaleService.canBuy(cartOrders.getCartOrderProducts(), memberId);
		}
		return "tlpCode";
	}

	public String checkOrderBuyTlp() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String memberId = StringUtils.defaultString(userData.getMemberId());
		tlpCode = timeLimitSaleService.canBuy(productId, memberId);
		return "tlpCode";
	}

	/**
	 * 检查赠品是否已被加入购物车
	 * 
	 * @return
	 */
	public String checkGiftExist() {
		CartOrders corders = cartordersService.getCart(UserLoginData.getMemberId(), null);
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("cartId", corders.getCartId());
		criteria.addEq("prodId", fromProduct);
		// List<CartOrderProduct> op = cartordersService.getCartOrderProductList(0, -1, criteria, null);
		List<CartOrderProduct> op = corders.getCartOrderProducts();
		if (null != op && op.size() > 0) {
			actionResult = "exist";
		} else {
			actionResult = "ok";
		}
		return "checkGiftExistOK";
	}

	// 確認數量
	public String checkSpecInventory() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));
		String memberId = StringUtils.defaultString(userData.getMemberId());

		String addCmpPd = request.getParameter("addCmpPd");
		String currentCartId = tmpCartid;
		if (buyNowCartId != null && buyNowCartId.length() > 0) {
			currentCartId = buyNowCartId;
		} else {
			if (memberId != null && memberId.length() > 0) {
				currentCartId = memberId;
			}
		}
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		optional.put("rePage", rsPage);
		// cartOrders = cartordersService.calculateCart(cartOrders, optional);

		String step = request.getParameter("checkFlag");
		if (step.indexOf("STEP0") >= 0) {
			step = "step0";
		}
		if (step.indexOf("STEP1") >= 0) {
			step = "step1";
		}
		if (step.indexOf("STEP2") >= 0) {
			step = "step2";
		}
		String acp = "";
		if (addCmpPd != null) {
			acp = StringUtils.defaultString(addCmpPd);
		}

		String invntryInfo = cartordersService.checkSpecInventory(currentCartId, acp, optional, step);
		actionResult = invntryInfo;
		/*
		 * if (request.getParameter("checkFlag").equals("STEP0M")) {// 确认主商品数量-step1 String acp = ""; if (addCmpPd != null)
		 * { acp = StringUtils.defaultString(addCmpPd); }
		 * 
		 * String invntryInfo = cartordersService.checkSpecInventory(currentCartId, acp, optional, "STEP0"); actionResult =
		 * invntryInfo; }
		 * 
		 * if (request.getParameter("checkFlag").equals("STEP1M")) {// 确认主商品数量-step1 String acp = ""; if (addCmpPd != null)
		 * { acp = StringUtils.defaultString(addCmpPd); }
		 * 
		 * String invntryInfo = cartordersService.checkSpecInventory(currentCartId, acp, optional, "STEP1"); actionResult =
		 * invntryInfo; } if (request.getParameter("checkFlag").equals("STEP1P")) {// 确认赠品数量-step1 String invntryInfo =
		 * cartordersService.checkSpecInventoryForPresent(currentCartId, optional); actionResult = invntryInfo; } if
		 * (request.getParameter("checkFlag").equals("STEP2M")) {// 确认主商品数量-step2 String acp = ""; if (addCmpPd != null) {
		 * acp = StringUtils.defaultString(addCmpPd); } //String invntryInfo =
		 * cartordersService.checkSpecInventoryTwo(currentCartId, acp); actionResult = invntryInfo; } if
		 * (request.getParameter("checkFlag").equals("STEP2P")) {// 确认赠品数量-step2 String invntryInfo =
		 * cartordersService.checkSpecInventoryTwoForPresent(currentCartId, optional); actionResult = invntryInfo; }
		 */
		return "cartdeleted";
	}

	// 確認數量-立即購買
	public String checkSpecInventoryBuyNow() throws Exception {
		// String invntryInfo = cartordersService.checkSpecInventoryBuyNow(chkInveny);
		// actionResult = invntryInfo;
		return "cartdeleted";
	}

	// 確認數量-立即購買-贈品
	public String checkSpecInventoryBuyNowForPresent() throws Exception {
		// String invntryInfo = cartordersService.checkSpecInventoryBuyNowForPresent(chkInveny);
		// actionResult = invntryInfo;
		return "cartdeleted";
	}

	/**
	 * 刪除cart by cartOrderProdId
	 * 
	 * @return
	 * @throws Exception
	 */
	public String delCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String flag = "error";
		crit = new CommonCriteria();
		CartOrders cart = cartordersService.get(cartId);
		Iterator<CartOrderProduct> it = cart.getCartOrderProducts().iterator();
		while (it.hasNext()) {
			CartOrderProduct cop = it.next();
			if (cop.getCartOrderProdId().equals(Long.valueOf(delCartProdId))) {
				for (CartOrderProductDetail copd : cop.getDetails()) {
					baseMgr.delete(copd);
				}
				baseMgr.delete(cop);
				it.remove();

				flag = "success";
				break;
			}
		}
		// cartordersService.save(cart);
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		cartOrders = cartordersService.calculateCart(cart, optional);
		// 记录购物车商品数量
		userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		actionResult = flag;
		tempTotalAmount = calcAmount(cartOrders);

		return "cartdeleted";
	}

	/**
	 * 刪除cart by cartOrderDetailId
	 * 
	 * @return
	 * @throws Exception
	 */
	public String delCartDetail() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String flag = "error";

		String hql = "from CartOrderProductDetail where cartOrderProdId=? and prodId=?";
		CartOrderProductDetail cartOrderProductDetail = (CartOrderProductDetail) baseMgr.queryByHql(hql, new Object[] {
				Long.parseLong(delCartOrderProdId), delCartProdId }, 0, 1)[0];

		CartOrders cart = cartordersService.get(cartOrderProductDetail.getCartId());
		Iterator<CartOrderProduct> it = cart.getCartOrderProducts().iterator();
		while (it.hasNext()) {
			CartOrderProduct cop = it.next();
			Iterator<CartOrderProductDetail> it2 = cop.getDetails().iterator();
			while (it2.hasNext()) {
				CartOrderProductDetail copd = it2.next();
				if (copd.getCartOrderProdId().equals(Long.valueOf(delCartOrderProdId))
						&& copd.getProdId().equals(delCartProdId)) {
					it2.remove();
					baseMgr.delete(copd);
					flag = "success";
				}
			}
		}
		// cartordersService.save(cart);
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		cartOrders = cartordersService.calculateCart(cart, optional);
		// 记录购物车商品数量
		userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		actionResult = flag;
		tempTotalAmount = calcAmount(cartOrders);
		return "cartdeleted";
	}

	public List<AddressBook> getAbList() {
		return abList;
	}

	public String getActionResult() {
		return actionResult;
	}

	public String getAddCmpnPrdctId() {
		return addCmpnPrdctId;
	}

	/**
	 * @return the addonProdId
	 */
	public String getAddonProdId() {
		return addonProdId;
	}

	public String getAddOns() {
		return addOns;
	}

	public AddPurchaseSetting getAddPurchaseSetting() {
		return addPurchaseSetting;
	}

	/**
	 * @return the buyNowCartId
	 */
	public String getBuyNowCartId() {
		return buyNowCartId;
	}

	public ArrayList<String> getBuyNowList() {
		return buyNowList;
	}

	public List<CampaignProduct> getCampaignProductList() {
		return campaignProductList;
	}

	public CampaignProductService getCampaignProductService() {
		return campaignProductService;
	}

	public int getCampaignProductSize() {
		return campaignProductSize;
	}

	/**
	 * 满额购商品查属性
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getCampaignProductSpec() throws Exception {
		Product cmpproduct = product2Service.get(addCmpnPrdctId);
		crit = new CommonCriteria();
		crit.addEq("productId", addCmpnPrdctId);
		crit.addEq("isDelete", "N");
		List<Specification> specificationList = product2Service.getSpecificationList(0, -1, crit, null);
		StringBuilder spcCmpProd = new StringBuilder();
		if (specificationList.size() > 0) {
			Specification specific = specificationList.get(0);
			spcCmpProd.append(specific.getSpecificationId());

		}
		crit = new CommonCriteria();
		crit.addEq("productId", addCmpnPrdctId);
		CampaignProduct campaignProduct = campaignProductService.getList(0, 1, crit, null).get(0);
		// 抓取價格
		Shelf cmpShelf = shelfService.getActiveShelfByProductId(addCmpnPrdctId);
		StringBuilder sbCampProd = new StringBuilder();
		sbCampProd.append(cmpproduct.getProductName()).append(",");// 商品名稱
		sbCampProd.append(spcCmpProd.toString()).append(",");// spec 名稱
		sbCampProd.append(cmpShelf.getShelfPrice().subtract(campaignProduct.getDiscount())).append(",");// 售價
		sbCampProd.append(cmpproduct.getProductWeight()).append(",");// 重量
		sbCampProd.append(cmpproduct.getIsDelete());// 銷售狀態
		actionResult = sbCampProd.toString();
		return "cartdeleted";
	}

	public List<Product> getCampainProductDataList() {
		return campainProductDataList;
	}

	public List<String> getCampainProductPriceList() {
		return campainProductPriceList;
	}

	public int getCanUse() {
		return canUse;
	}

	/**
	 * @return the carItemList
	 */
	public ArrayList<String> getCarItemList() {
		return carItemList;
	}

	public String getCartId() {
		return cartId;
	}

	/**
	 * @return the cartOrderProdId
	 */
	public String getCartOrderProdId() {
		return cartOrderProdId;
	}

	public List<CartOrderProductDetail> getCartOrderProductDetailList() {
		return cartOrderProductDetailList;
	}

	public List<CartOrderProduct> getCartOrderProductList() {
		return cartOrderProductList;
	}

	public CartOrders getCartOrders() {
		return cartOrders;
	}

	/**
	 * @return the cartordersService
	 */
	public CartOrdersService getCartordersService() {
		return cartordersService;
	}

	public String[] getCategoryPath() {
		return categoryPath;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public String getChkInveny() {
		return chkInveny;
	}

	public String getCity() {
		return city;
	}

	public Product getCmpPord() {
		return cmpPord;
	}

	public String getCmpPordId() {
		return cmpPordId;
	}

	public String getCmpUuid() {
		return cmpUuid;
	}

	public int getCountBuyNow() {
		return countBuyNow;
	}

	public String getDelCartOrderProdId() {
		return delCartOrderProdId;
	}

	public String getDelCartProdId() {
		return delCartProdId;
	}

	public String getDistrict() {
		return district;
	}

	public String getFromCategory() {
		return fromCategory;
	}

	public String getFromProduct() {
		return fromProduct;
	}

	public String getItemExists() {
		return itemExists;
	}

	public String[] getItemNo() {
		return itemNo;
	}

	public AddressBook getLastAddressBook() {
		return lastAddressBook;
	}

	/**
	 * @return the member
	 */
	public Member getMember() {
		return member;
	}

	/**
	 * @return the memberService
	 */
	public MemberService getMemberService() {
		return memberService;
	}

	public String getMoveCartResult() {
		return moveCartResult;
	}

	public String getOverOneThousand() {
		return overOneThousand;
	}

	public Map<String, Map<String, List<String>>> getPickMap() {
		return pickMap;
	}

	public String getPresents() {
		return presents;
	}

	/**
	 * @return the prodQty
	 */
	public String getProdQty() {
		return prodQty;
	}

	/**
	 * @return the prodSpecId
	 */
	public String getProdSpecId() {
		return prodSpecId;
	}

	/**
	 * @return the product
	 */
	public Product getProduct() {
		return product;
	}

	public Menu getProductTpMenu() {
		return productTpMenu;
	}

	public String getProvince() {
		return province;
	}

	public String[] getQty() {
		return qty;
	}

	public Map<String, String> getResultMap() {
		return resultMap;
	}

	public ShelfService getShelfService() {
		return shelfService;
	}

	public Map<String, String> getShowWeightMap() {
		return showWeightMap;
	}

	/**
	 * @return the specification
	 */
	public Specification getSpecification() {
		return specification;
	}

	public String[] getSpecNo() {
		return specNo;
	}

	public BigDecimal getTotalWeight() {
		return totalWeight;
	}

	public String[] getType() {
		return type;
	}

	public String getUpdateCartData() {
		return updateCartData;
	}

	/**
	 * @return the viewEcCartList
	 */
	public List<ViewEcCartDetail> getViewEcCartList() {
		return viewEcCartList;
	}

	public ArrayList<String> getViewEcCartNewList() {
		return viewEcCartNewList;
	}

	/*
	 * 結帳－更新購物車資料
	 */
	public String goOrderInfo() throws Exception {
		String flag = "success";

		actionResult = flag;
		return "cartdeleted";
	}

	private boolean isItemExists(CartOrders tmpCartOrders, String[] itemNos, String[] specNos, String tempCartId) {
		boolean isExists = false;
		if (tmpCartOrders == null) {
			tmpCartOrders = (CartOrders) baseMgr.get(CartOrders.class, tempCartId);
			if (tmpCartOrders == null) {
				tmpCartOrders = new CartOrders();
			}
		}

		List<CartOrderProduct> cops = tmpCartOrders.getCartOrderProducts();
		for (CartOrderProduct cop : cops) {
			String copSpecId = cop.getProdSpecId();
			String copProdId = cop.getProdId();
			if (itemNo != null) {
				for (String itemId : itemNo) {
					if (copProdId.equals(itemId)) {
						for (String specId : specNo) {
							if (copSpecId.equals(specId)) {
								isExists = true;
							}
						}
					}
				}
			}
		}

		return isExists;
	}

	private boolean isTlpItemExists(CartOrders tmpCartOrders, String[] itemNos, String tempCartId) {
		boolean isTlpExists = false;
		if (tmpCartOrders == null) {
			tmpCartOrders = (CartOrders) baseMgr.get(CartOrders.class, tempCartId);
			if (tmpCartOrders == null) {
				tmpCartOrders = new CartOrders();
			}
		}

		List<CartOrderProduct> cops = tmpCartOrders.getCartOrderProducts();
		for (CartOrderProduct cop : cops) {
			String copProdId = cop.getProdId();
			if (itemNo != null) {
				for (String itemId : itemNo) {
					if (copProdId.equals(itemId)) {
						isTlpExists = true;
					}
				}
			}
		}
		return isTlpExists;
	}

	// 立即购买(已登入的库存数json检查)
	public String orderBuyNowJson() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String memberId = StringUtils.defaultString(userData.getMemberId());
		userData.writeRawValue(UserData.NAME_YAODIAN100_TL_RS, ServerValue.getFrontContextPath()
				+ "/product/product.do?productId=" + itemNo[0]);
		List<String> addOnProductIds = new ArrayList<String>();
		String[] addOnsSplit = null;
		if (addOns != null) {
			addOnsSplit = addOns.split(",");
			for (String str : addOnsSplit) {
				addOnProductIds.add(StringUtils.remove(str, "\""));
			}
		}
		logger.info("xxx01");
		cartOrders = cartordersService.getCart(memberId, null);
		logger.info("xxx0");
		if (cartOrders != null) {
			// 不需初始化購物車
		} else {
			cartordersService.createCart(memberId, null, null, null, 0, null, null);

		}
		logger.info("xxx1");
		String categoryId = NumberUtils.isNumber(categoryPath[0]) ? categoryPath[0] : StringUtils
				.parseNumber(categoryPath[0]);
		if ("6".equals(type[0])) {
			cartOrders = cartordersService.createCart(memberId, itemNo[0], addOnProductIds, Long.valueOf(specNo[0]), Integer
					.valueOf(qty[0]), categoryId, null);
		} else {
			cartOrders = cartordersService.createCart(memberId, itemNo[0], null, Long.valueOf(specNo[0]), Integer
					.valueOf(qty[0]), categoryId, addOnProductIds);
		}
		logger.info("xxx2");
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		optional.put("rsPage", "buy");
		cartOrders = cartordersService.calculateCart(cartOrders, optional);
		request.setAttribute("isBuyNow", "true");

		String invntryInfo = cartordersService.checkSpecInventory(cartOrders.getCartId(), "", optional, "step0Login");
		logger.info("xxx3");
		actionResult = invntryInfo;
		logger.info("actionResult:{}", actionResult);
		if ("OK".equalsIgnoreCase(actionResult) || actionResult.indexOf("赠品") > 0) {
			// 删除立即购买购物车
			cartordersService.delete(cartOrders);
		}
		return "orderBuyNowJson";
	}

	// 立即購買
	public String orderBuyNow() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String memberId = StringUtils.defaultString(userData.getMemberId());
		userData.writeRawValue(UserData.NAME_YAODIAN100_TL_RS, ServerValue.getFrontContextPath()
				+ "/product/product.do?productId=" + itemNo[0]);
		List<String> addOnProductIds = new ArrayList<String>();
		String[] addOnsSplit = null;
		if (addOns != null) {
			addOnsSplit = addOns.split(",");
			for (String str : addOnsSplit) {
				addOnProductIds.add(StringUtils.remove(str, "\""));
			}
		}
		cartOrders = cartordersService.getCart(memberId, null);

		if (cartOrders != null) {
			// 不需初始化購物車
		} else {
			cartordersService.createCart(memberId, null, null, null, 0, null, null);

		}
		String categoryId = NumberUtils.isNumber(categoryPath[0]) ? categoryPath[0] : StringUtils
				.parseNumber(categoryPath[0]);
		if ("6".equals(type[0])) {
			cartOrders = cartordersService.createCart(memberId, itemNo[0], addOnProductIds, Long.valueOf(specNo[0]), Integer
					.valueOf(qty[0]), categoryId, null);
		} else {
			cartOrders = cartordersService.createCart(memberId, itemNo[0], null, Long.valueOf(specNo[0]), Integer
					.valueOf(qty[0]), categoryId, addOnProductIds);
		}
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		optional.put("rsPage", "buy");
		cartOrders = cartordersService.calculateCart(cartOrders, optional);
		request.setAttribute("isBuyNow", "true");
		if (StringUtils.isBlank(request.getParameter("prtFlag"))) {
			String invntryInfo = cartordersService.checkSpecInventory(cartOrders.getCartId(), "", optional, "step0");
			actionResult = invntryInfo;
		} else {
			cartOrders = updPrtQty(cartOrders);
			cartOrders = cartordersService.calculateCart(cartOrders, optional);
			actionResult = "";
		}

		// 限時搶購
		if (timeLimitSaleService.isTimeLimitSale(itemNo[0])) {
			timeLimitCartOrderProductList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());
		}

		BigDecimal cartSumAmount = cartOrders.getAmount().add(cartOrders.getDiscount());
		// // 会员积分使用限制
		// if (null != bonusSettingService.getLowestDiscount(cartSumAmount)) {
		// bonusSetting = bonusSettingService.getLowestDiscount(cartSumAmount);
		// }
		// 行銷活動-会员积分折抵比例
		bonusCampaign = campaignService.getActiveBonusCampaignByM02(optional);

		// COD﹣收取手續費
		codFee = addressService.getCodFee();

		// 是否需要輸入驗證碼
		needValidateNum = cartordersService.needValidateNum(cartOrders.getCartId());
		deliveryType = deliveryRuleService.findDeliveryType("cart", cartOrders.getCartId()).get("deliveryType");
		// logger.info("deliveryType:{}", deliveryType);
		// 地址簿-省
		provincesMap = deliveryRuleService.getCartProvinces(cartOrders.getCartId());

		// 限制COD付款
		canUseCod = deliveryRuleService.chkProdDetailCanUseCod("cart", cartOrders.getCartId());

		// 信用卡分期
		creditcard = creditcardService.getValidCreditcard(itemNo[0], userData.getApplySource(), request.getServerName());

		tempTotalAmount = calcAmount(cartOrders);
		if (null != creditcard && tempTotalAmount > 0) {
			chkAvailableDetails = creditcardService
					.chkAvailableCreditCardDetails(creditcard, new BigDecimal(tempTotalAmount));
		}

		billBankCodeMenu = menuService.get("99Bill.BankCode");

		// 检核是否做过手机验证
		ismobileVaild = member.getIsMobileMember();

		// 大材积商品
		prodVolumeMap = cartordersService.chkVolumeOfCartOrderDetail(cartOrders.getCartId());

		return "orderBuyNow";
	}

	// 购物车总额(不含折扣/运费)
	Float calcAmount(CartOrders cartOrders) {
		tempTotalAmount = 0f;
		if (null != cartOrders && cartOrders.getProductSum() > 0) {
			for (CartOrderProduct prod : cartOrders.getCartOrderProducts()) {
				for (CartOrderProductDetail detail : prod.getDetails()) {
					tempTotalAmount = tempTotalAmount + detail.getAmount().floatValue() * detail.getQty();
				}
			}
		}
		return tempTotalAmount;
	}

	public void prepare() throws Exception {
		clearErrorsAndMessages();
		try {
			if (productTpMenu == null) {
				productTpMenu = menuService.get("Product.Type");
			}
			addPurchaseSetting = addPurchaseSettingService.getCurrentAddPurchaseSetting();
			if (null != addPurchaseSetting) {
				campaignProductList = campaignProductService.getProductsByOrderAmount(addPurchaseSetting.getBasePrice(), null,
						20);
				campainProductDataList = new ArrayList<Product>();
				campainProductPriceList = new ArrayList<String>();
				campaignProductSize = campaignProductList.size();
				if (campaignProductSize > 0) {
					Product product = null;
					Map<String, SpecificationInventory> inventories = null;
					int inventorySum = 0;
					int i = 0;
					for (CampaignProduct campaignProduct : campaignProductList) {
						product = product2Service.get(campaignProduct.getProductId());
						if (null != product) {
							// 檢查商品狀態
							if (!product.getIsDelete().equalsIgnoreCase("Y") && product.getProductStatus().equalsIgnoreCase("PRD500")) {
								inventories = product2Service.getSpecificationInventoryMap(product.getProductId());
								// 檢查是否有庫存檔案
								if (null != inventories && inventories.size() > 0) {
									inventorySum = 0;
									for (SpecificationInventory inventory : inventories.values()) {
										if ("N".equalsIgnoreCase(inventory.getSpecification().getIsDelete())) {
											inventorySum = inventorySum + inventory.getInventory();
										}
									}
									// 檢查庫存量是否大於0
									if (inventorySum > 0 && i <= 8) {
										StringBuilder sb = new StringBuilder();
										sb.append(product.getProductId()).append(",").append(product.getProductName()).append(",").append(
												product.getListPrice()).append(",").append(campaignProduct.getPrice()).append(",").append(
												campaignProduct.getUuid()).append(",").append(product.getProductWeight());
										campainProductDataList.add(i, product);
										campainProductPriceList.add(i, sb.toString());
										i++;
									}
								}
							}
						}
					}
					if (!campainProductPriceList.isEmpty()) {
						campaignProductSize = campainProductPriceList.size();
					}
				}
			}
			// 会员积分
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			UserData userData = new UserData(request, response);
			if (null != userData && null != userData.getMemberId()) {
				member = memberService.get(userData.getMemberId());
				if (null != member) {
					Map<String, String> optional = new HashMap<String, String>();
					optional.put("domain", request.getServerName());
					optional.put("cookie", userData.getApplySource());
					bonusCampaign = campaignService.getActiveBonusCampaignByM02(optional);
					if (null != bonusCampaign) {
						bonusCampaign.getJsonDetail();
						// 將积分換算為錢,可使用多少积分
						Balance balance = member.getBalance();
						canUse = balance.getBonusBalance().intValue() / Integer.parseInt(bonusCampaign.getOffsetRate());
					}
					// overOneThousand = transferService.checkOverOneThousandBonus(member.getMemberId());
					overOneThousand = "N";
				} else {
					canUse = 0;
				}

			}
			// 免运费活动
			CommonCriteria cri = new CommonCriteria();
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			cri.addGe("endDateTime", format.parse(DateUtil.convertDateToString("yyyy-MM-dd HH:mm:ss", DateUtil.getToday()
					.getTime())));
			cri.addLe("startDateTime", format.parse(DateUtil.convertDateToString("yyyy-MM-dd HH:mm:ss", DateUtil.getToday()
					.getTime())));
			cri.addEq("enable", true);
			campaignList = campaignDiscountService.getList(0, -1, cri, null);
			campaignDiscount = new CampaignDiscount();
			if (campaignList.size() > 0) {
				campaignDiscount = campaignList.get(0);
			}
		} catch (CoreException e) {
			e.printStackTrace();
		}
		clearErrorsAndMessages();
	}

	public String reloadCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String tmpCartId = StringUtils.defaultString(userData.readRawValue("cartid"));
		String memberId = StringUtils.defaultString(userData.getMemberId());
		// 瀏覽器裏已有cookie就放入tmpCartid
		// viewEcCartList = null;
		// 帳號登入
		if (StringUtils.isNotBlank(memberId)) {
			cartOrders = cartordersService.getCart(memberId, null);
		} else {
			if (StringUtils.isNotBlank(tmpCartId)) {
				cartOrders = cartordersService.getCart(null, tmpCartId);
				if (null == cartOrders) {
					cartOrders = new CartOrders();
				}
				resultMap = weightMap(cartOrders);
			}
		}

		if (null == cartOrders) {
			cartOrders = new CartOrders();
		} else {
			Map<String, String> optional = new HashMap<String, String>();
			optional.put("domain", request.getServerName());
			optional.put("cookie", userData.getApplySource());
			cartOrders = cartordersService.calculateCart(cartOrders, optional);
		}

		fromProduct = StringUtils.defaultString(userData.readRawValue("fromProduct"));
		fromCategory = StringUtils.defaultString(userData.readRawValue("fromCategory"));
		// 记录购物车商品数量
		userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		tlpList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());
		// 限時搶購商品
		tlpCode = timeLimitSaleService.canBuy(cartOrders.getCartOrderProducts(), memberId);
		if (!StringUtils.equals("2", tlpCode)) {
			addActionMessage(tlpCode);
		}
		return "showcart";
	}

	public String forceReloadCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		HttpSession session = request.getSession();
		UserData userData = new UserData(request, response);
		String tmpCartId = StringUtils.defaultString(userData.readRawValue("cartid"));
		String memberId = StringUtils.defaultString(userData.getMemberId());
		// 瀏覽器裏已有cookie就放入tmpCartid
		// viewEcCartList = null;
		// 帳號登入
		if (StringUtils.isNotBlank(memberId)) {
			cartOrders = cartordersService.getCart(memberId, null);
			cartOrders = cartordersService.forceUpdateCart(cartOrders);
		} else {
			if (StringUtils.isNotBlank(tmpCartId)) {
				cartOrders = cartordersService.getCart(null, tmpCartId);
				if (null == cartOrders) {
					cartOrders = new CartOrders();
				}
				resultMap = weightMap(cartOrders);
			}
		}

		if (null == cartOrders) {
			cartOrders = new CartOrders();
		} else {
			Map<String, String> optional = new HashMap<String, String>();
			optional.put("domain", request.getServerName());
			optional.put("cookie", userData.getApplySource());
			cartOrders = cartordersService.calculateCart(cartOrders, optional);
		}

		fromProduct = StringUtils.defaultString(userData.readRawValue("fromProduct"));
		fromCategory = StringUtils.defaultString(userData.readRawValue("fromCategory"));
		// 记录购物车商品数量
		userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		tlpList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());
		// 限時搶購商品
		tlpCode = timeLimitSaleService.canBuy(cartOrders.getCartOrderProducts(), memberId);
		if (!StringUtils.equals("2", tlpCode)) {
			addActionMessage(tlpCode);
		}
		if (null != cartOrders.getCartOrderProducts()) {
			// 百分点推荐引擎sessionid
			String sessionId = userData.getSessionId();
			if (null == sessionId || StringUtils.isBlank(sessionId)) {
				userData.writeValue(UserData.NAME_YAODIAN100_SESSION_ID, session.getId());
			}
			// 百分點商品推薦

			StringBuffer sb100Item = new StringBuffer();
			int i = 1;
			StringBuffer cartItem = new StringBuffer();

			for (CartOrderProduct opItem : cartOrders.getCartOrderProducts()) {
				if (opItem.getUnitPrice().compareTo(BigDecimal.ZERO) == 1) {
					sb100Item.append("p.a").append(i).append(" = new brs.AddShopCart(");
					if (StringUtils.isNotBlank(userData.getMemberId())) {
						sb100Item.append("'").append(userData.getMemberId()).append("',");
					} else {
						sb100Item.append("'").append(userData.getSessionId()).append("',");
					}
					sb100Item.append("'").append(opItem.getProdId()).append("',");
					sb100Item.append("'").append(userData.getSessionId()).append("');\n");
					i++;
					cartItem.append("'").append(opItem.getProdId()).append("',");
				}
			}
			if (cartItem.length() > 0) {
				sb100Item.append("p.recSC = new brs.RecByShoppingCart(new Array(").append(
						cartItem.substring(0, cartItem.length() - 1)).append("),'").append(userData.getSessionId()).append(
						"',40);\n");
				cart100Items = sb100Item.toString();
			}
		}

		// 大材积商品
		prodVolumeMap = cartordersService.chkVolumeOfCartOrderDetail(cartOrders.getCartId());

		// 购物车总额(不含折扣/运费)
		tempTotalAmount = calcAmount(cartOrders);

		return "showcart";
	}

	public String returnToCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		request.setAttribute("cartMessage", request.getAttribute("cartMessage"));
		// request.setAttribute("cartMessage", "订单金额与预期不符，请检查购物车！");
		return reloadCart();
	}

	public String showCampaignProduct() throws Exception {
		if (StringUtils.isNotBlank(cmpnPrdctId)) {
			campaignProduct = campaignProductService.get(cmpnPrdctId);
			if (null != campaignProduct) {
				product = product2Service.get(campaignProduct.getProductId());
				if (null != product.getSpecMajors()) {
					isVolumeOfProduct = product2Service.chkVolumeOfProduct(campaignProduct.getProductId());
					prodMajors = product.getActivateSpecMajors();
					prodInvMap = product2Service.getSpecificationInventoryMap(campaignProduct.getProductId());
				}
			}
		}
		return "dialogCampaignProduct";
	}

	public void setAbList(List<AddressBook> abList) {
		this.abList = abList;
	}

	public void setActionResult(String actionResult) {
		this.actionResult = actionResult;
	}

	public void setAddCmpnPrdctId(String addCmpnPrdctId) {
		this.addCmpnPrdctId = addCmpnPrdctId;
	}

	/**
	 * @param addonProdId the addonProdId to set
	 */
	public void setAddonProdId(String addonProdId) {
		this.addonProdId = addonProdId;
	}

	public void setAddOns(String addOns) {
		this.addOns = addOns;
	}

	public void setAddPurchaseSetting(AddPurchaseSetting addPurchaseSetting) {
		this.addPurchaseSetting = addPurchaseSetting;
	}

	public void setAddPurchaseSettingService(AddPurchaseSettingService addPurchaseSettingService) {
		this.addPurchaseSettingService = addPurchaseSettingService;
	}

	/**
	 * @param buyNowCartId the buyNowCartId to set
	 */
	public void setBuyNowCartId(String buyNowCartId) {
		this.buyNowCartId = buyNowCartId;
	}

	public void setBuyNowList(ArrayList<String> buyNowList) {
		this.buyNowList = buyNowList;
	}

	public void setCampaignProductList(List<CampaignProduct> campaignProductList) {
		this.campaignProductList = campaignProductList;
	}

	public void setCampaignProductService(CampaignProductService campaignProductService) {
		this.campaignProductService = campaignProductService;
	}

	public void setCampaignProductSize(int campaignProductSize) {
		this.campaignProductSize = campaignProductSize;
	}

	public void setCampainProductDataList(List<Product> campainProductDataList) {
		this.campainProductDataList = campainProductDataList;
	}

	public void setCampainProductPriceList(List<String> campainProductPriceList) {
		this.campainProductPriceList = campainProductPriceList;
	}

	public void setCanUse(int canUse) {
		this.canUse = canUse;
	}

	/**
	 * @param carItemList the carItemList to set
	 */
	public void setCarItemList(ArrayList<String> carItemList) {
		this.carItemList = carItemList;
	}

	public void setCartId(String cartId) {
		this.cartId = cartId;
	}

	/**
	 * @param cartOrderProdId the cartOrderProdId to set
	 */
	public void setCartOrderProdId(String cartOrderProdId) {
		this.cartOrderProdId = cartOrderProdId;
	}

	public void setCartOrderProductDetailList(List<CartOrderProductDetail> cartOrderProductDetailList) {
		this.cartOrderProductDetailList = cartOrderProductDetailList;
	}

	public void setCartOrderProductList(List<CartOrderProduct> cartOrderProductList) {
		this.cartOrderProductList = cartOrderProductList;
	}

	public void setCartOrders(CartOrders cartOrders) {
		this.cartOrders = cartOrders;
	}

	/**
	 * @param cartordersService the cartordersService to set
	 */
	public void setCartordersService(CartOrdersService cartordersService) {
		this.cartordersService = cartordersService;
	}

	public void setCategoryPath(String[] categoryPath) {
		this.categoryPath = categoryPath;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public void setChkInveny(String chkInveny) {
		this.chkInveny = chkInveny;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public void setCmpPord(Product cmpPord) {
		this.cmpPord = cmpPord;
	}

	public void setCmpPordId(String cmpPordId) {
		this.cmpPordId = cmpPordId;
	}

	public void setCmpUuid(String cmpUuid) {
		this.cmpUuid = cmpUuid;
	}

	public void setCountBuyNow(int countBuyNow) {
		this.countBuyNow = countBuyNow;
	}

	public void setDelCartOrderProdId(String delCartOrderProdId) {
		this.delCartOrderProdId = delCartOrderProdId;
	}

	public void setDelCartProdId(String delCartProdId) {
		this.delCartProdId = delCartProdId;
	}

	public void setDistrict(String district) {
		this.district = district;
	}

	public void setFromCategory(String fromCategory) {
		this.fromCategory = fromCategory;
	}

	public void setFromProduct(String fromProduct) {
		this.fromProduct = fromProduct;
	}

	public void setItemExists(String itemExists) {
		this.itemExists = itemExists;
	}

	public void setItemNo(String[] itemNo) {
		this.itemNo = itemNo;
	}

	public void setLastAddressBook(AddressBook lastAddressBook) {
		this.lastAddressBook = lastAddressBook;
	}

	/**
	 * @param member the member to set
	 */
	public void setMember(Member member) {
		this.member = member;
	}

	/**
	 * @param memberService the memberService to set
	 */
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public void setMoveCartResult(String moveCartResult) {
		this.moveCartResult = moveCartResult;
	}

	public void setOverOneThousand(String overOneThousand) {
		this.overOneThousand = overOneThousand;
	}

	public void setPickMap(Map<String, Map<String, List<String>>> pickMap) {
		this.pickMap = pickMap;
	}

	public void setPresents(String presents) {
		this.presents = presents;
	}

	/**
	 * @param prodQty the prodQty to set
	 */
	public void setProdQty(String prodQty) {
		this.prodQty = prodQty;
	}

	/**
	 * @param prodSpecId the prodSpecId to set
	 */
	public void setProdSpecId(String prodSpecId) {
		this.prodSpecId = prodSpecId;
	}

	/**
	 * @param product the product to set
	 */
	public void setProduct(Product product) {
		this.product = product;
	}

	public void setProductTpMenu(Menu productTpMenu) {
		this.productTpMenu = productTpMenu;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public void setQty(String[] qty) {
		this.qty = qty;
	}

	public void setResultMap(Map<String, String> resultMap) {
		this.resultMap = resultMap;
	}

	public void setShelfService(ShelfService shelfService) {
		this.shelfService = shelfService;
	}

	public void setShowWeightMap(Map<String, String> showWeightMap) {
		this.showWeightMap = showWeightMap;
	}

	/**
	 * @param specification the specification to set
	 */
	public void setSpecification(Specification specification) {
		this.specification = specification;
	}

	public void setSpecNo(String[] specNo) {
		this.specNo = specNo;
	}

	public void setTotalWeight(BigDecimal totalWeight) {
		this.totalWeight = totalWeight;
	}

	public void setTransferService(TransferService transferService) {
		this.transferService = transferService;
	}

	public void setType(String[] type) {
		this.type = type;
	}

	public void setUpdateCartData(String updateCartData) {
		this.updateCartData = updateCartData;
	}

	/**
	 * @param viewEcCartList the viewEcCartList to set
	 */
	public void setViewEcCartList(List<ViewEcCartDetail> viewEcCartList) {
		this.viewEcCartList = viewEcCartList;
	}

	public void setViewEcCartNewList(ArrayList<String> viewEcCartNewList) {
		this.viewEcCartNewList = viewEcCartNewList;
	}

	// 商品重量計算
	public String showBuyNowWeight() throws Exception {
		resultMap = buyNowWeight(chkInveny, cartId);
		return "showWeight";
	}

	/**
	 * 计算总重量
	 * 
	 * @return
	 * @throws Exception
	 */
	public String showTotalWeight() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		cartOrders = cartordersService.get(userData.readRawValue("cartid"));
		showWeightMap = weightMap(cartOrders);
		return "jsonWeightMap";
	}

	// 商品重量計算
	public String showWeight() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);

		cartId = StringUtils.defaultString(userData.readRawValue("cartid"));
		String memberId = StringUtils.defaultString(userData.getMemberId());
		String currentCartId = cartId;
		if (memberId != null && memberId.length() > 0) {
			currentCartId = memberId;
		}
		if (StringUtils.isNotBlank(currentCartId)) {
			cartOrders = cartordersService.get(currentCartId);
			resultMap = weightMap(cartOrders);
		} else {
			resultMap = new HashMap<String, String>();
			resultMap.put("totalWeight", new BigDecimal(0).setScale(3).toString());
		}
		return "showWeight";
	}

	public String updateCart() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);

		String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));
		String memberId = StringUtils.defaultString(userData.getMemberId());

		cartOrders = cartordersService.getCart(memberId, tmpCartid);
		String hql = "from SpecificationInventory where specId=?";

		String cartMessage = "";
		for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {

			if (cop.getCartOrderProdId() == Long.parseLong(cartOrderProdId)) {
				// 加購商品更改數量
				if (addonProdId != null && addonProdId.length() > 0) {

					for (CartOrderProductDetail copd : cop.getDetails()) {
						if (copd.getProdId().equals(addonProdId)) {
							// 檢查庫存
							SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { copd
									.getProdSpecId() }, 0, 1)[0];
							Integer inventory = si.getInventory();
							// do something
							if (inventory <= 0) {
								// 庫存不足
								cartMessage += "庫存不足無法購買！";
								copd.setQty(0);
							} else if (inventory < Integer.parseInt(prodQty)) {
								// 庫存量少於所選數量
								cartMessage += "庫存数量不足于所选的数量，已调整为：" + inventory;
								copd.setQty(inventory);
							} else {
								copd.setQty(Integer.parseInt(prodQty));
							}
							break;
						}
					}
				} else

				// 主商品更改數量，prodSpecId要一併傳回
				if (prodQty != null) {
					Integer selectProdQty = Integer.parseInt(prodQty);
					// 檢查庫存
					CartOrderProduct copCurrent = (CartOrderProduct) baseMgr.get(CartOrderProduct.class, Long
							.valueOf(cartOrderProdId));
					SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { copCurrent
							.getProdSpecId() }, 0, 1)[0];
					Integer inventory = si.getInventory();
					Product product = (Product) baseMgr.get(Product.class, si.getProductId());
					// Integer maxQty=product.getMaxPOQuantity();
					// Integer minQty=product.getMinPOQuantity();
					// TODO

					if (inventory <= 0) {
						cartMessage += "所选属性库存不足";
					} else {
						if (selectProdQty > inventory) {
							// 庫存量少於所選數量
							cartMessage += "库存不足，已调整为：" + inventory;
							cop.setProdSpecId(prodSpecId);
							cop.setQty(inventory);
						} else {
							cop.setQty(selectProdQty);
						}

						cartMessage += updateCartDetail(cop, copCurrent);

					}
				} else
				// 主商品更改屬性
				{

					// 檢查庫存
					CartOrderProduct copCurrent = (CartOrderProduct) baseMgr.get(CartOrderProduct.class, Long
							.valueOf(cartOrderProdId));
					SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { prodSpecId }, 0,
							1)[0];
					Integer inventory = si.getInventory();

					if (inventory <= 0) {
						cartMessage += "所选属性库存不足";
					} else {
						if (cop.getQty() > inventory) {
							// 庫存量少於所選數量
							cartMessage += "所选属性数量不足于所选的数量，已调整为：" + inventory;
							cop.setProdSpecId(prodSpecId);
							cop.setProdSpecName(si.getSpecification().getSpecificationName());
							cop.setQty(inventory);
						} else {
							cop.setProdSpecId(prodSpecId);
							cop.setProdSpecName(si.getSpecification().getSpecificationName());
						}

						cartMessage += updateCartDetail(cop, copCurrent);

					}
				}

				break;
			}
		}

		cartordersService.update(cartOrders);
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		cartOrders = cartordersService.calculateCart(cartOrders, optional);
		request.setAttribute("cartMessage", cartMessage);
		return "reloadCart";
	}

	private String updateCartDetail(CartOrderProduct cop, CartOrderProduct copCurrent) {
		String cartMessage = "";
		String hql = "from SpecificationInventory where specId=?";

		for (CartOrderProductDetail copd : cop.getDetails()) {
			// 调整主商品spec
			if (copd.getProdSpecId().equals(copCurrent.getProdSpecId())) {
				copd.setProdSpecId(cop.getProdSpecId());
				copd.setProdSpecName(cop.getProdSpecName());
				copd.setQty(cop.getQty());
			} else

			// 調整加購商品數量
			if (copd.getDetailTp().equals(Product.PRODUCT_TYPE.ADDON.getValue())) {
				// 檢查庫存

				SpecificationInventory siad = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { copd
						.getProdSpecId() }, 0, 1)[0];
				Integer inventoryad = siad.getInventory();
				if (copd.getQty() > cop.getQty()) {
					copd.setQty(cop.getQty());
				}
				if (copd.getQty() > inventoryad) {
					cartMessage += " 调整加购商品数量";
					copd.setQty(inventoryad);
				}
				/*
				 * // do something if (inventoryad <= 0) { // 庫存不足 cartMessage += "加购商品库存不足无法购买！"; copd.setQty(0);
				 * 
				 * } else { // 调整加购商品数量 if (copd.getQty() > inventoryad && cop.getQty() > inventoryad) { cartMessage +=
				 * " 调整加购商品数量"; copd.setQty(inventoryad); } else if (copd.getQty() > cop.getQty() && inventoryad >
				 * copd.getQty()) { copd.setQty(cop.getQty()); } else { // ?? } }
				 */
				break;
			} else
			// 赠品
			if (copd.getDetailTp().equals(Product.PRODUCT_TYPE.PRESENT.getValue())) {
				// 檢查庫存
				SpecificationInventory sips = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { copd
						.getProdSpecId() }, 0, 1)[0];
				Integer inventoryps = sips.getInventory();
				copd.setQty(cop.getQty());
				if (copd.getQty() > inventoryps) {
					cartMessage += " 赠品库存不足，已调整为：" + inventoryps;
					copd.setQty(inventoryps);
				}
				/*
				 * if (inventoryps <= 0) { cartMessage += " 赠品库存不足！"; copd.setQty(0); } else {
				 * 
				 * // 調整贈品數量 if (inventoryps > cop.getQty()) { copd.setQty(cop.getQty()); } else { cartMessage +=
				 * " 赠品库存不足，已调整为：" + inventoryps; copd.setQty(inventoryps); } }
				 */
			}
			baseMgr.update(copd);
		}

		// baseMgr.update(cop);
		return cartMessage;
	}

	Map<String, String> weightMap(CartOrders cartOrders) throws Exception {
		cartOrderProductList = cartOrders.getCartOrderProducts();
		cartOrderProductDetailList = new ArrayList<CartOrderProductDetail>();
		Shelf shelf = null;
		for (CartOrderProduct product : cartOrderProductList) {
			for (CartOrderProductDetail detail : product.getDetails()) {
				if (Arrays.asList("0", "1").contains(detail.getDetailTp())) {
					shelf = shelfService.getActiveShelfByProductId(detail.getProdId());
					if (null != shelf && detail.getQty() > 0) {
						cartOrderProductDetailList.add(detail);
					}
				} else if ("5".equals(detail.getDetailTp())) {
					CampaignProduct cp = campaignProductService.getProduct(detail.getProdId());
					if (null != cp
							&& DateUtil.checkDateBetween(DateUtil.getCurrentTime(), cp.getStartDateTime(), cp.getEndDateTime(), true,
									true) && detail.getQty() > 0) {
						cartOrderProductDetailList.add(detail);
					}
				} else if (Arrays.asList("2", "3", "4", "6").contains(detail.getDetailTp())) {
					cartOrderProductDetailList.add(detail);
				}
			}
		}
		Map<String, String> weightMap = cartordersService.showProductWeight(cartOrderProductDetailList);
		return weightMap;
	}

	public String jsonChkValidateNum() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		member = memberService.getMemberByLoginId(userData.getLoginId());
		try {
			ccodeResult = "";
			cartOrderService.checkCode(userData.getImageValid(), ccode);
			ccodeResult = "ok";
		} catch (Exception e) {
			ccodeResult = "error";
		}
		return "jsonChkValidateNum";
	}

	public String jsonChkValidCreditcardDetail() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		CreditcardDetail creditcardDetail = creditcardService.getValidCreditcard(productId, creditcardDetailId, period,
				userData.getApplySource(), request.getServerName());
		if (null == creditcardDetail) {
			creditcardDetailResult = "error";
		} else {
			if (MapUtils.isNotEmpty(creditcardDetail.getDownLimitMap())
					&& MapUtils.isNotEmpty(creditcardDetail.getUpLimitMap())) {
				if (null == creditcardDetail.getPeriodMap().get(period)
						|| Float.valueOf(finalTotalAmount) < Float.valueOf(creditcardDetail.getDownLimitMap().get(period))
						|| Float.valueOf(finalTotalAmount) > Float.valueOf(creditcardDetail.getUpLimitMap().get(period))) {// 不符合分期期數的上下限
					creditcardDetailResult = "error";
				} else {
					creditcardDetailResult = "ok";
				}
			}
		}
		return "jsonChkValidCreditcard";
	}

	/**
	 * 载入各银行分期付款期数&手续费
	 * 
	 * @return
	 * @throws Exception
	 */
	public String jsonGetCreditcardDetail() throws Exception {
		CreditcardDetail creditcardDetail = creditcardDetailService.get(Long.parseLong(creditcardDetailId));
		creditcardDetailEntity = creditcardDetail;

		return "jsonGetCreditcardDetail";
	}

	public List<CampaignDiscount> getCampaignList() {
		return campaignList;
	}

	public void setCampaignList(List<CampaignDiscount> campaignList) {
		this.campaignList = campaignList;
	}

	public CampaignDiscount getCampaignDiscount() {
		return campaignDiscount;
	}

	public void setCampaignDiscount(CampaignDiscount campaignDiscount) {
		this.campaignDiscount = campaignDiscount;
	}

	public String getAddCartResult() {
		return addCartResult;
	}

	public void setAddCartResult(String addCartResult) {
		this.addCartResult = addCartResult;
	}

	public List<String> getTlpList() {
		return tlpList;
	}

	public void setTlpList(List<String> tlpList) {
		this.tlpList = tlpList;
	}

	public TimeLimitSaleService getTimeLimitSaleService() {
		return timeLimitSaleService;
	}

	public void setTimeLimitSaleService(TimeLimitSaleService timeLimitSaleService) {
		this.timeLimitSaleService = timeLimitSaleService;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public String getRs() {
		return rs;
	}

	public void setRs(String rs) {
		this.rs = rs;
	}

	public String getTlpCode() {
		return tlpCode;
	}

	public void setTlpCode(String tlpCode) {
		this.tlpCode = tlpCode;
	}

	public List<String> getTimeLimitCartOrderProductList() {
		return timeLimitCartOrderProductList;
	}

	public void setTimeLimitCartOrderProductList(List<String> timeLimitCartOrderProductList) {
		this.timeLimitCartOrderProductList = timeLimitCartOrderProductList;
	}

	public BonusSetting getBonusSetting() {
		return bonusSetting;
	}

	public void setBonusSetting(BonusSetting bonusSetting) {
		this.bonusSetting = bonusSetting;
	}

	public BigDecimal getCodFee() {
		return codFee;
	}

	public void setCodFee(BigDecimal codFee) {
		this.codFee = codFee;
	}

	public void setAddressService(AddessService addressService) {
		this.addressService = addressService;
	}

	public String getRsPage() {
		return rsPage;
	}

	public void setRsPage(String rsPage) {
		this.rsPage = rsPage;
	}

	public boolean isNeedValidateNum() {
		return needValidateNum;
	}

	public void setNeedValidateNum(boolean needValidateNum) {
		this.needValidateNum = needValidateNum;
	}

	public String getCcode() {
		return ccode;
	}

	public void setCcode(String ccode) {
		this.ccode = ccode;
	}

	public String getCcodeResult() {
		return ccodeResult;
	}

	public void setCcodeResult(String ccodeResult) {
		this.ccodeResult = ccodeResult;
	}

	public Map<String, String> getProvincesMap() {
		return provincesMap;
	}

	public void setProvincesMap(Map<String, String> provincesMap) {
		this.provincesMap = provincesMap;
	}

	public String getDeliveryType() {
		return deliveryType;
	}

	public void setDeliveryType(String deliveryType) {
		this.deliveryType = deliveryType;
	}

	public boolean isCanUseCod() {
		return canUseCod;
	}

	public void setCanUseCod(boolean canUseCod) {
		this.canUseCod = canUseCod;
	}

	public String getCart100Items() {
		return cart100Items;
	}

	public void setCart100Items(String cart100Items) {
		this.cart100Items = cart100Items;
	}

	public String getCreditcardDetailId() {
		return creditcardDetailId;
	}

	public String getPeriod() {
		return period;
	}

	public String getCreditcardDetailResult() {
		return creditcardDetailResult;
	}

	public Creditcard getCreditcard() {
		return creditcard;
	}

	public Menu getBillBankCodeMenu() {
		return billBankCodeMenu;
	}

	public CreditcardDetail getCreditcardDetailEntity() {
		return creditcardDetailEntity;
	}

	public void setCreditcardDetailId(String creditcardDetailId) {
		this.creditcardDetailId = creditcardDetailId;
	}

	public void setPeriod(String period) {
		this.period = period;
	}

	public void setCreditcardDetailResult(String creditcardDetailResult) {
		this.creditcardDetailResult = creditcardDetailResult;
	}

	public void setCreditcard(Creditcard creditcard) {
		this.creditcard = creditcard;
	}

	public void setBillBankCodeMenu(Menu billBankCodeMenu) {
		this.billBankCodeMenu = billBankCodeMenu;
	}

	public void setCreditcardDetailEntity(CreditcardDetail creditcardDetailEntity) {
		this.creditcardDetailEntity = creditcardDetailEntity;
	}

	public String getFinalTotalAmount() {
		return finalTotalAmount;
	}

	public void setFinalTotalAmount(String finalTotalAmount) {
		this.finalTotalAmount = finalTotalAmount;
	}

	public boolean isIsmobileVaild() {
		return ismobileVaild;
	}

	public void setIsmobileVaild(boolean ismobileVaild) {
		this.ismobileVaild = ismobileVaild;
	}

	public Map<String, String> getProdVolumeMap() {
		return prodVolumeMap;
	}

	public void setProdVolumeMap(Map<String, String> prodVolumeMap) {
		this.prodVolumeMap = prodVolumeMap;
	}

	public Map<String, SpecificationInventory> getProdInvMap() {
		return prodInvMap;
	}

	public void setProdInvMap(Map<String, SpecificationInventory> prodInvMap) {
		this.prodInvMap = prodInvMap;
	}

	public CampaignProduct getCampaignProduct() {
		return campaignProduct;
	}

	public String getCmpnPrdctId() {
		return cmpnPrdctId;
	}

	public List<SpecificationMajor> getProdMajors() {
		return prodMajors;
	}

	public void setCampaignProduct(CampaignProduct campaignProduct) {
		this.campaignProduct = campaignProduct;
	}

	public void setCmpnPrdctId(String cmpnPrdctId) {
		this.cmpnPrdctId = cmpnPrdctId;
	}

	public void setProdMajors(List<SpecificationMajor> prodMajors) {
		this.prodMajors = prodMajors;
	}

	public boolean isVolumeOfProduct() {
		return isVolumeOfProduct;
	}

	public void setVolumeOfProduct(boolean isVolumeOfProduct) {
		this.isVolumeOfProduct = isVolumeOfProduct;
	}

	public String getCmpSpecId() {
		return cmpSpecId;
	}

	public void setCmpSpecId(String cmpSpecId) {
		this.cmpSpecId = cmpSpecId;
	}

	public Float getTempTotalAmount() {
		return tempTotalAmount;
	}

	public void setTempTotalAmount(Float tempTotalAmount) {
		this.tempTotalAmount = tempTotalAmount;
	}

	public boolean isChkAvailableDetails() {
		return chkAvailableDetails;
	}

	public void setChkAvailableDetails(boolean chkAvailableDetails) {
		this.chkAvailableDetails = chkAvailableDetails;
	}

	public Campaign getBonusCampaign() {
		return bonusCampaign;
	}

	public void setBonusCampaign(Campaign bonusCampaign) {
		this.bonusCampaign = bonusCampaign;
	}
}